<?

## used for connecting to the mysql db
function mysqlconnect($mysql_user, $mysql_password, $mysql_db) {
	$link = mysql_connect('localhost', $mysql_user, $mysql_password);
	if (!$link) {
		die('Could not connect: ' . mysql_error());
	}
	else {
		mysql_select_db($mysql_db) or die(mysql_error());
	}
}
mysqlconnect($site['mysql_user'], $site['mysql_password'], $site['mysql_db']);


## used for checking regular user sessions
function checksession($sessid, $ipaddress) {	
	// query mysql for matching session id and ip address - this is inserted using the login session function/creator
	$sql = mysql_query("select * from user_sessions where us_sessionid = '".$sessid."' && us_ipaddress = '".$ipaddress."'");
	if ($result = mysql_fetch_array($sql)) {
		return true;
	} else {
		return false;
	}
}



## clean up input from user - do not use for HTML input or carriage return-sensitive content (will not preserve line return formatting)
function cleanup($in) {
	$out = "";	
	$out = strip_tags($in);
	$out = trim($out);
	$out = mysql_real_escape_string($out);
	$out = htmlspecialchars($out);
	return $out;
}


## clean up form input for HTML based content or to preserve carriage return formatting
function cleanhtml($in) {
	$out = strip_tags($in, '<p><a><strong><em><u><ol><li><ul>');
	$out = mysql_real_escape_string($out);
	$out = htmlspecialchars($out);
	return $out;
}

## used for stripping slashes
function strip($in) {
	if (get_magic_quotes_gpc() == 0) {
		$out = stripslashes($in);
	} else {
		$out = $in;
	}
	return $out;
}

## test for a valid e-mail address in format and by valid domain
function is_valid_email_address($email) {
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex) {
      $isValid = false;
   } else {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64) {
         // local part length exceeded
         $isValid = false;
      } else if ($domainLen < 1 || $domainLen > 255) {
         // domain part length exceeded
         $isValid = false;
      } else if ($local[0] == '.' || $local[$localLen-1] == '.') {
         // local part starts or ends with '.'
         $isValid = false;
      } else if (preg_match('/\\.\\./', $local)) {
         // local part has two consecutive dots
         $isValid = false;
      } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
         // character not valid in domain part
         $isValid = false;
      } else if (preg_match('/\\.\\./', $domain)) {
         // domain part has two consecutive dots
         $isValid = false;
      } else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) {
         // character not valid in local part unless 
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}




## grab page name (sans extension) and use as page id -- used in the menu
function grabpagename() {
	$filename = strtolower($_SERVER['SCRIPT_NAME']);
	$filearray = split("/", $filename);
	$filearray[1] = str_replace(".php", "", $filearray[1]);
	$filearray[2] = str_replace(".php", "", $filearray[2]);
	
	if ($filearray[1] == "mfci") {
		$pageid = $filearray[2];
	} else {
		$pageid = $filearray[1];
	}
	
	return $pageid;
}


## password generator for reset password
function generatePassword($length=9, $strength=0) {
		$vowels = 'aeuy';
		$consonants = 'bdghjmnpqrstvz';
		if ($strength & 1) {
			$consonants .= 'BDGHJLMNPQRSTVWXZ';
		}
		if ($strength & 2) {
			$vowels .= "AEUY";
		}
		if ($strength & 4) {
			$consonants .= '23456789';
		}
		if ($strength & 8) {
			$consonants .= '@#$%';
		}

		$password = '';
		$alt = time() % 2;
		for ($i = 0; $i < $length; $i++) {
			if ($alt == 1) {
				$password .= $consonants[(rand() % strlen($consonants))];
				$alt = 0;
			} else {
				$password .= $vowels[(rand() % strlen($vowels))];
				$alt = 1;
			}
		}
		return $password;
	}


## for page redirects
function redirectCountdown($redirectpage, $countdowntime, $redirectmessage) {
	
	if ($countdowntime == "") $countdowntime = 3;

	$output = "<p>".$redirectmessage." in <input type=\"text\" size=\"1\" id=\"redirect\" style=\"border: 0px; padding: 0px; margin: 0px; text-align: right;\" /> seconds</p>\n";
	$output .= "<script>\n";
	$output .= "<!--\n";
	$output .= "var targetURL=\"".$redirectpage."\";\n";
	$output .= "var countdownfrom=".$countdowntime.";\n";
	
	$output .= "var currentsecond=document.getElementById(\"redirect\").value=countdownfrom+1;\n";
	$output .= "function countredirect(){\n";
	$output .= "	if (currentsecond!=1){\n";
	$output .= "		currentsecond-=1;\n";
	$output .= "		document.getElementById(\"redirect\").value=currentsecond;\n";
	$output .= "	} else {\n";
	$output .= "	window.location=targetURL;\n";
	$output .= "	return;\n";
	$output .= "	}\n";
	$output .= "	setTimeout(\"countredirect()\",1000);\n";
	$output .= "}\n";
	$output .= "countredirect();\n";
	$output .= "//-->\n";
	$output .= "</script>\n";

	echo $output;

}

## send mail function - at the moment sends only straight text, but can be converted to send HTML
function SendMail($sendername, $senderemail, $toname, $toemail, $subject, $messagetext) {
	

	# -=-=-=- PHP FORM VARIABLES (add as many as you would like)	
	
	# -=-=-=- MIME BOUNDARY	
	$mime_boundary = "----boundary----".md5(time());
	
	# -=-=-=- MAIL HEADERS	
	$to = $toemail;
	//$subject = "This text will display in the email's Subject Field";
	
	$headers = "From: ".$sendername." <".$senderemail.">\n";
	$headers .= "Reply-To: ".$sendername." <".$senderemail.">\n";
	//$headers .= "MIME-Version: 1.0\n";
	//$headers .= "Content-Type: multipart/alternative; boundary=\"$mime_boundary\"\n";	
	# -=-=-=- TEXT EMAIL PART	
	//$message = "--$mime_boundary\n";
	//$message .= "Content-Type: text/plain; charset=UTF-8\n";
	//$message .= "Content-Transfer-Encoding: 8bit\n\n";
	
	$message .= $messagetext;
	
	//$message .= "$name:\n\n";
	//$message .= "This email is to confirm that \"Our Company\" has received your order.\n";
	//$message .= "Please send payment of $invoicetotal to our company address.\n\n";
	//$message .= "Thank You.\n\n";
	
	# -=-=-=- HTML EMAIL PART
	 
	//$message .= "--$mime_boundary\n";
	//$message .= "Content-Type: text/html; charset=UTF-8\n";
	//$message .= "Content-Transfer-Encoding: 8bit\n\n";
	
	//$message .= $messagehtml;
	
	//$message .= "<html>\n";
	//$message .= "<body style=\"font-family:Verdana, Verdana, Geneva, sans-serif; font-size:14px; color:#666666;\">\n";
	//$message .= "$name:<br>\n";
	//$message .= "<br>\n";
	//$message .= "This email is to confirm that \"Our Company\" has received your order.<br>\n";
	//$message .= "</body>\n";
	//$message .= "</html>\n";
	
	# -=-=-=- FINAL BOUNDARY
	
	//$message .= "--$mime_boundary--\n\n";
	
	# -=-=-=- SEND MAIL
	
	$mailit = mail( $to, $subject, $message, $headers );
	//$mailit .= $to."<br />".$subject."<br />".$message."<br />".$headers."<br />";
	
	return $mailit;
	//$mail_sent = @mail( $to, $subject, $message, $headers );
	//return $mail_sent;
	//return $mail_sent ? "Mail sent" : "Mail failed";

}



?>